package com.nstar.sinaweibo.model
{
	import com.nstar.base.util.Downloader;
	import com.nstar.base.util.LoadXMLDelegate;
	import com.nstar.base.util.Logger;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.filesystem.File;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.IResponder;

	/**
	 * 主题加载器
	 * 加载配置的主题
	 * 
	 */ 
	public class ThemeLoader extends EventDispatcher  implements IResponder 
	{
		private var loader:LoadXMLDelegate;
		private var url:String ;
		
		private var _themes:ArrayCollection = new ArrayCollection();
		private var logger:Logger = Logger.getInstance(this);
		
		public function ThemeLoader(url:String)
		{
			trace("themes config url : "+url);
			this.url = url;
			loader = new LoadXMLDelegate(this,this.url,"object");
			loader.load();
			logger.debug("loading themes...");	
		}
		
		//加载
		public function load():void{
			loader.load();
		}
		
		public function result(data:Object):void{
			_themes.removeAll();
			var tempThemes:Object = data.result.styles.style;
			if(tempThemes is ArrayCollection){
				for each(var item:Object in tempThemes){
					var themeVO:ThemeVO = transThemeVO(item);
					_themes.addItem(themeVO);
				}
			}else{
				var themeVO:ThemeVO = transThemeVO(tempThemes);
				_themes.addItem(themeVO);
			}
			//下载样式
			logger.debug("load themes config xml ok. ["+_themes.length+" themes]");
			
			if(_themes.length > 0){
				download(_themes);
			}
						
			this.dispatchEvent(new Event(Event.COMPLETE));
		}
		
		private function transThemeVO(item:Object):ThemeVO{
			var themeVO:ThemeVO = new ThemeVO();
			themeVO.seq = item.seq;
			themeVO.name = item.name;
			themeVO.previewImageUrl = item.previewImageUrl;
			themeVO.description = item.description;
			themeVO.url = item.url;
			return themeVO;
		}	
		
		public function fault(info:Object):void{
			logger.debug("load themes config xml error!!"+info.fault.faultDetail);
		}
		
		//下载样式
		public function download(themes:ArrayCollection):void{
			//检查有无新的样式文件
			var files:Array = new Array();
			for each(var theme:ThemeVO in themes){
				var fileName:String = Utils.getFileName(theme.url);
				//检查文件是否存在
				var themeFile:File = new File(File.applicationDirectory.resolvePath("themes/"+fileName).nativePath);
				//如果文件不存在，则下载文件
				if(themeFile.exists == false){
					files.push(fileName);
					
					//下载样式swf文件
					logger.debug(fileName+" does not exists,downloading now ...");
					var swfDownloader:Downloader = new Downloader();
					swfDownloader.download(theme.url,"themes");
				}
			}
			
			if(files.length>0){
				logger.debug("find "+files.length+" new themes to download.");
			}else{
				logger.debug("no themes to update~");
			}
			
		}
		
		public function get themes():ArrayCollection{
			return _themes;
		}		
	}
}